package ro.pub.cs.ncit.webviewer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;

public class WebDownloader extends AsyncTask<String, Void, String>{
	
	private TaskListener taskListener;
	
	@Override
	protected String doInBackground(String... params) {
		String url = params[0];
		String contents = "";
		
		InputStream inputStream = null;
		
		HttpClient client = new DefaultHttpClient();
		try {
			HttpResponse response = client.execute(new HttpGet(url));
			inputStream = response.getEntity().getContent();
			
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
			String line;
			while((line=bufferedReader.readLine())!= null){
				contents += line;
			}
			
			inputStream.close();
			bufferedReader.close();
			
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return contents;
	}
	
	@Override
	protected void onPostExecute(String param){
		if(taskListener != null){
			taskListener.onTaskComplete(param);
		}
	}
	
	public void setTaskListener(TaskListener taskListener){
		this.taskListener = taskListener;
	}
}